package logic

import (
	"context"
	"errors"
	"good/goodrpc/goodrpc"
	"good/goodrpc/internal/svc"
	"good/models/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodAddLogic {
	return &GoodAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodAddLogic) GoodAdd(in *goodrpc.GoodAddRequest) (*goodrpc.GoodAddResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("id=?", in.UserId).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}

	good := mysql.Good{
		Title:     in.Title,
		Image:     in.Image,
		Price:     float64(in.Price),
		ClassName: in.ClassName,
		Info:      in.Info,
		UserId:    int(in.UserId),
		ClassId:   int(in.ClassId),
	}
	if good.Title == "" && good.ClassName == "" && good.Info == "" && good.Price == 0 {
		return nil, errors.New("标题、分类、价格、描述等必填项")
	}

	mysql.DB.Debug().Create(&good)

	return &goodrpc.GoodAddResponse{
		GoodId: int64(good.ID),
	}, nil
}
